// 任务数据存储
let tasks = JSON.parse(localStorage.getItem('tasks')) || [];

// DOM元素
const taskInput = document.getElementById('new-task');
const addTaskBtn = document.getElementById('add-task');
const taskList = document.getElementById('task-list');
const taskCount = document.getElementById('task-count');
const filterButtons = document.querySelectorAll('.filter-btn');
let currentFilter = 'all';

// 初始化应用
function init() {
    renderTasks();
    updateTaskCount();
    
    // 添加事件监听器
    addTaskBtn.addEventListener('click', addTask);
    taskInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') addTask();
    });
    
    filterButtons.forEach(button => {
        button.addEventListener('click', () => {
            filterButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            currentFilter = button.dataset.filter;
            renderTasks();
        });
    });
}

// 添加新任务
function addTask() {
    const text = taskInput.value.trim();
    if (text) {
        const newTask = {
            id: Date.now(),
            text,
            completed: false
        };
        tasks.push(newTask);
        saveTasks();
        taskInput.value = '';
        renderTasks();
        updateTaskCount();
    }
}

// 渲染任务列表
function renderTasks() {
    taskList.innerHTML = '';
    
    let filteredTasks = tasks;
    if (currentFilter === 'active') {
        filteredTasks = tasks.filter(task => !task.completed);
    } else if (currentFilter === 'completed') {
        filteredTasks = tasks.filter(task => task.completed);
    }
    
    if (filteredTasks.length === 0) {
        taskList.innerHTML = '<p class="no-tasks">暂无任务</p>';
        return;
    }
    
    filteredTasks.forEach(task => {
        const taskItem = document.createElement('li');
        taskItem.className = 'task-item';
        taskItem.dataset.id = task.id;
        
        taskItem.innerHTML = `
            <input type="checkbox" class="task-checkbox" ${task.completed ? 'checked' : ''}>
            <span class="task-text ${task.completed ? 'completed' : ''}">${task.text}</span>
            <div class="task-actions">
                <button class="task-btn edit">✏️</button>
                <button class="task-btn delete">🗑️</button>
            </div>
        `;
        
        taskList.appendChild(taskItem);
    });
    
    // 添加事件监听器到新创建的元素
    document.querySelectorAll('.task-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', toggleTask);
    });
    
    document.querySelectorAll('.task-btn.edit').forEach(btn => {
        btn.addEventListener('click', editTask);
    });
    
    document.querySelectorAll('.task-btn.delete').forEach(btn => {
        btn.addEventListener('click', deleteTask);
    });
}

// 切换任务完成状态
function toggleTask(e) {
    const taskId = parseInt(e.target.closest('.task-item').dataset.id);
    const task = tasks.find(task => task.id === taskId);
    task.completed = e.target.checked;
    saveTasks();
    renderTasks();
    updateTaskCount();
}

// 编辑任务
function editTask(e) {
    const taskItem = e.target.closest('.task-item');
    const taskId = parseInt(taskItem.dataset.id);
    const task = tasks.find(task => task.id === taskId);
    const taskText = taskItem.querySelector('.task-text');
    
    const input = document.createElement('input');
    input.type = 'text';
    input.value = task.text;
    input.className = 'edit-input';
    
    taskText.replaceWith(input);
    input.focus();
    
    function saveEdit() {
        const newText = input.value.trim();
        if (newText) {
            task.text = newText;
            saveTasks();
        }
        renderTasks();
    }
    
    input.addEventListener('blur', saveEdit);
    input.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') saveEdit();
    });
}

// 删除任务
function deleteTask(e) {
    const taskId = parseInt(e.target.closest('.task-item').dataset.id);
    tasks = tasks.filter(task => task.id !== taskId);
    saveTasks();
    renderTasks();
    updateTaskCount();
}

// 更新剩余任务计数
function updateTaskCount() {
    const activeTasks = tasks.filter(task => !task.completed).length;
    taskCount.textContent = activeTasks;
}

// 保存任务到本地存储
function saveTasks() {
    localStorage.setItem('tasks', JSON.stringify(tasks));
}

// 初始化应用
init();